package com.uduemc.biso.node.web.api.service.impl;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.uduemc.biso.core.extities.center.Host;
import com.uduemc.biso.core.extities.center.Site;
import com.uduemc.biso.core.utils.FileZip;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.dto.TemplateTempCache;
import com.uduemc.biso.node.core.common.feign.CTemplateFeign;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.core.utils.SitePathUtil;
import com.uduemc.biso.node.web.api.service.HostService;
import com.uduemc.biso.node.web.api.service.SiteService;
import com.uduemc.biso.node.web.api.service.TemplateService;

@Service
public class TemplateServiceImpl implements TemplateService {

	public static String redisKeyPrefix = "Template_Cache_";

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private HostService hostServiceImpl;

	@Autowired
	private SiteService siteServiceImpl;

	@Autowired
	private CTemplateFeign cTemplateFeign;

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public int makeTemplateZip(long hostId, long siteId, String key) throws Exception {

		// 通过 hostId 获取 Host 数据
		Host host = hostServiceImpl.getInfoById(hostId);
		if (host == null) {
			return -1;
		}

		Site site = siteServiceImpl.getInfoById(hostId, siteId);
		if (site == null) {
			return -2;
		}

		// 生成临时文件目录
		String tempPath = makeTemplateTempPath(hostId, siteId, key);

		// 将网站目录下的资源目录、favicon.ico图标拷贝到临时文件目录下
		copyTemplateRepertory(tempPath, host, site);

		// 站点数据生成json文件并且有序的拷贝到临时目录下
		boolean makeTemplateDataJson = makeTemplateDataJson(tempPath, host, site);
		if (!makeTemplateDataJson) {
			return -3;
		}

		// 生成验证文件
		File zipFile = new File(tempPath + "/verification");
		if (zipFile.isFile()) {
			zipFile.delete();
		}
		long sizeOfDirectory = FileUtils.sizeOfDirectory(new File(tempPath + "/data"));
		FileUtils.writeStringToFile(zipFile, DigestUtils.md5DigestAsHex(String.valueOf(sizeOfDirectory).getBytes()),
				"UTF-8", true);

		// 压缩操作，
		FileZip.compress(tempPath, tempPath);

		// 删除临时的压缩目录
		FileUtils.deleteDirectory(new File(tempPath));

		TemplateTempCache templateTempCache = new TemplateTempCache();

		long sizeOf = FileUtils.sizeOf(new File(tempPath + ".zip"));

		templateTempCache.setHostId(hostId).setSiteId(siteId).setKey(key).setZipPath(tempPath + ".zip")
				.setZipSize(sizeOf);

		// 操作完成后在缓存中将临时压缩文件完整路径保存至键为key当中
		redisUtil.set(makeTemplateRedisKey(key), templateTempCache, 60 * 30);

		return 0;
	}

	@Override
	public String makeTemplateTempPath(long hostId, long siteId, String key) throws IOException {
		String tempPath = globalProperties.getSite().getTempPath();
		String path = tempPath + "/template/" + hostId + "_" + siteId + "_" + key;
		File file = new File(path);
		if (file.isDirectory()) {
			FileUtils.deleteDirectory(file);
		}
		File zipFile = new File(path + ".zip");
		if (zipFile.isFile()) {
			FileUtils.deleteQuietly(zipFile);
		}
		FileUtils.forceMkdir(file);
		return path;
	}

	@Override
	public void copyTemplateRepertory(String tempPath, Host host, Site site) throws IOException {
		String tempHomePath = tempPath + "/home";
		File tempHomeFile = new File(tempHomePath);
		if (!tempHomeFile.isDirectory()) {
			FileUtils.forceMkdir(tempHomeFile);
		}
		String userRepertoryPathByCode = SitePathUtil
				.getUserRepertoryPathByCode(globalProperties.getSite().getBasePath(), host.getRandomCode());
		File userFile = new File(userRepertoryPathByCode);
		if (userFile.isDirectory()) {
			FileUtils.copyDirectoryToDirectory(userFile, tempHomeFile);
		}
	}

	@Override
	public void copyTemplateFavicon(String tempPath, Host host, Site site) throws IOException {
		String tempHomePath = tempPath + "/home";
		File tempHomeFile = new File(tempHomePath);
		if (!tempHomeFile.isDirectory()) {
			FileUtils.forceMkdir(tempHomeFile);
		}
		// 获取 favicon.ico 文件路径
		String userPathByCode = SitePathUtil.getUserPathByCode(globalProperties.getSite().getBasePath(),
				host.getRandomCode());
		String faviconPath = userPathByCode + "/favicon.ico";
		File faviconFile = new File(faviconPath);
		if (faviconFile.isFile()) {
			// 如果存在
			FileUtils.copyFileToDirectory(faviconFile, tempHomeFile);
		}
	}

	@Override
	public boolean makeTemplateDataJson(String tempPath, Host host, Site site) throws IOException {
		String tempDataPath = tempPath + "/data";
		RestResult restResult = cTemplateFeign.read(host.getId(), site.getId(), tempDataPath);
		Integer data = RestResultUtil.data(restResult, Integer.class);
		if (data != null && data.intValue() == 1) {
			return true;
		}
		return false;
	}

	@Override
	public String makeTemplateRedisKey(String key) {
		return TemplateServiceImpl.redisKeyPrefix + key;
	}

	@Override
	public boolean isTemplateRedisKey(String key) {
		return key.startsWith(TemplateServiceImpl.redisKeyPrefix);
	}

	@Override
	public TemplateTempCache getTemplateTempCache(String key) {
		TemplateTempCache templateTempCache = (TemplateTempCache) redisUtil.get(makeTemplateRedisKey(key));
		return templateTempCache;
	}

}
